package com.skytech.component.crawler.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.Charset;


@Service
public class HttpClientPost {
    private static final String URL = "http://114.116.1.157:6080/crawler/crawler/listDataByTypeAndTime";
    private static final String APP_KEY = "skytech";
    private static final String SECRET_KEY = "crawler@password";

    /**
     * 构造Basic Auth认证头信息
     *
     * @return
     */
    private String getHeader() {
        String auth = APP_KEY + ":" + SECRET_KEY;
        byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
        String authHeader = "Basic " + new String(encodedAuth);
        return authHeader;
    }

    // HttpClientContext context = HttpClientContext.create();


    public JSONObject send1(JSONObject pushObject) {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(URL);
        System.out.println("要发送的数据" + JSON.toJSONString(pushObject));
        StringEntity myEntity = new StringEntity(JSON.toJSONString(pushObject), ContentType.APPLICATION_JSON);// 构造请求数据
        post.addHeader("Authorization", getHeader());
        post.setEntity(myEntity);// 设置请求体
        String responseContent = null; // 响应内容
        CloseableHttpResponse response = null;
        try {
            response = client.execute(post);
            System.out.println(JSON.toJSONString(response));
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                responseContent = EntityUtils.toString(entity, "UTF-8");
            }
            //return  JSONObject.parseObject(responseContent);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null)
                    response.close();

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (client != null)
                        client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return JSONObject.parseObject(responseContent);
    }

    HttpClientContext context = HttpClientContext.create();

    public void addUserOAuth(String username, String password) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        Credentials credentials = new UsernamePasswordCredentials(username, password);
        credsProvider.setCredentials(AuthScope.ANY, credentials);
        this.context.setCredentialsProvider(credsProvider);
    }


    public JSONObject send(JSONObject jsonObject) throws Exception {
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(URL);
        // 设置请求的参数
       // List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        StringEntity myEntity = new StringEntity(JSON.toJSONString(jsonObject), ContentType.APPLICATION_JSON);// 构造请求数据
        httpPost.addHeader("Authorization", getHeader());
        httpPost.setEntity(myEntity);// 设置请求体

        //httpPost.setEntity(new UrlEncodedFormEntity(jsonObject, "utf-8"));
        // 执行请求
        addUserOAuth(APP_KEY, SECRET_KEY);
        String responseContent = null; // 响应内容
        HttpResponse response = httpClient.execute(httpPost, context);
        // 打印执行结果
        responseContent=EntityUtils.toString(response.getEntity(), "utf-8");
        return JSONObject.parseObject(responseContent);
    }


}
